package a66weding.com.jiehuntong.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.andview.refreshview.XRefreshView;
import com.google.gson.Gson;

import org.greenrobot.eventbus.Subscribe;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.adapter.FriendListAdapter;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.FriendsListBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.PersonBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.User;
import a66weding.com.jiehuntong.common.MessageEvent;
import a66weding.com.jiehuntong.common.api.Url;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.StrUtil;
import a66weding.com.jiehuntong.common.utils.Tools;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;
import a66weding.com.jiehuntong.inner.OnClickItem;
import a66weding.com.jiehuntong.inner.OnItemClickLitener;
import a66weding.com.jiehuntong.scanner.CaptureActivity;
import a66weding.com.jiehuntong.widgets.DividerItemDecoration;
import a66weding.com.jiehuntong.widgets.popuwindows.PopupWindowUtils;

/**
 * Created by admin on 2016/7/5.
 * 我的帮友界面;
 */
public class FindHelp extends Activity implements View.OnClickListener,OnNetResultListener,OnItemClickLitener,OnClickItem{
    //显示的布局;
    private ImageView diy_add;
    //定义标题栏弹窗按钮
    private PopupWindowUtils popupWindowUtils;
    private RelativeLayout findHelp_back;
    private XRefreshView xRefreshView;
    private RecyclerView recyclerView;
    private FriendListAdapter friendListAdapter;
    private boolean  isDownRefresh = true;
    private final static int SCANNIN_GREQUEST_CODE = 1;
    public static String ADDFRIENDSACTIVITY = "AddFriendsActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.diy_pag_findhelp);
        initView();
        initRefreshView();
        getNetData();
        Tools.setContext(this);
        Tools.showDialog(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.diy_add:
                popupWindowUtils.PopShowDown(v);
                break;
            case R.id.findHelp_back:
                finish();
                break;

        }
    }
    public void initView(){
        popupWindowUtils = new PopupWindowUtils(this);
        popupWindowUtils.setOnClickItem(this);
        diy_add = (ImageView) findViewById(R.id.diy_add);
        diy_add.setOnClickListener(this);
        findHelp_back = (RelativeLayout) findViewById(R.id.findHelp_back);
        findHelp_back.setOnClickListener(this);

    }

    //初始化上啦刷新
    private void initRefreshView() {
        xRefreshView = (XRefreshView)findViewById(R.id.help_xrefreshview);
        //是否允许下拉刷新
        xRefreshView.setPullRefreshEnable(true);
        // 设置是否可以上拉加载
        xRefreshView.setPullLoadEnable(true);
        // 设置刷新完成以后，headerview固定的时间
        xRefreshView.setPinnedTime(1000);
        // 静默加载模式不能设置footerview
        // 设置支持自动刷新
        xRefreshView.setAutoLoadMore(true);
        recyclerView = (RecyclerView)findViewById(R.id.help_recycler_view_test_rv);
        recyclerView.setHasFixedSize(true);
        //线性布局

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

       friendListAdapter = new FriendListAdapter(this,null);
        friendListAdapter.setOnItemClickLitener(this);
        recyclerView.setAdapter(friendListAdapter);
        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL_LIST));
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

            @Override
            public void onRefresh() {
                isDownRefresh = true;
                getNetData();
            }

            @Override
            public void onLoadMore(boolean isSlience) {
                isDownRefresh = false;
                getNetData();
            }
        });
    }


    private FriendsListBean bean;
    private List<FriendsListBean.DataBean> DataBean;
    private PersonBean personBean;
    private List<PersonBean.DataBean> personlist;
    private CommonResultBean commonResultBean;
    @Override
    public void onSucess(SuccessBean sucessbean) {
        Tools.dismissWaitDialog();
        Object data = sucessbean.getData();
        if(data instanceof FriendsListBean){
            bean = (FriendsListBean) data;
            /**
             * FriendsListBean
             * {ResCode='0000', Msg='成功', Data=[
             * DataBean{nvc_TitlePhoto='http://img1.66wedding.com/MemberLogo/2016/8/10/8c1613ab-4d26-4afd-8e24-25e10638218d.jpg',
             * MemberRID=343, RelationName='', CanEdit=false, Name='', IsAgreeA=0, IsAgreeB=1},
             * DataBean{nvc_TitlePhoto='http://img1.66wedding.com/MemberLogo/2016/8/10/8c1613ab-4d26-4afd-8e24-25e10638218d.jpg', MemberRID=343, RelationName='',
             * CanEdit=false, Name='', IsAgreeA=0, IsAgreeB=1},
             * DataBean{nvc_TitlePhoto='http://img1.66wedding.com/MemberLogo/2016/8/10/8c1613ab-4d26-4afd-8e24-25e10638218d.jpg', MemberRID=343, RelationName='',
             * CanEdit=false, Name='', IsAgreeA=0, IsAgreeB=1}]}
             IsAgreeA
             我是否同意
             IsAgreeB
             好友是否同意
             */
            if (isDownRefresh){
                xRefreshView.stopRefresh();
            }else{
                xRefreshView.stopLoadMore();
            }
            switch (bean.getResCode()){
                case "0000":
                    //刷新UI
                    DataBean = bean.getData();
                    if (isDownRefresh){
                        //如果你是下拉刷新,我就情况列表
                      friendListAdapter.clear();
                    }
                    friendListAdapter.append(getFilter(DataBean));

                    break;
            }

            if(data instanceof  PersonBean){
                personBean = (PersonBean) data;
               switch (personBean.getResCode()){
                   case "0000":
                       personlist = personBean.getData();
                      // 过滤数据;
                       Intent intent = new Intent(this,AddFrinds_2_Actvitiy.class);
                       intent.putExtra(ADDFRIENDSACTIVITY,(Serializable) personlist);
                       startActivity(intent);
                       break;
               }
            }

            if (data instanceof CommonResultBean){
                commonResultBean = (CommonResultBean) data;
                switch (commonResultBean.getResCode()){
                    case "0000":
                        CUtils.showToast("添加好友成功了");
                        break;
                }
            }
        }
    }

    private List<FriendsListBean.DataBean> getFilter(List<FriendsListBean.DataBean> list){
        if (list.size()>1){
            List<FriendsListBean.DataBean> friends =list;
            for (int i  = 0 ;i<list.size();i++){
                for (int j  = list.size()-1 ;j>i;j--){
                    if (list.get(i).getMemberRID()==friends.get(j).getMemberRID()){
                        friends.remove(j);
                    }
                }
            }
            return friends;
        }
        return list;
    }
    @Override
    public void onError(ErrorBean errorBean) {
        Tools.dismissWaitDialog();
    }

    public void getNetData(){

        String useUrl = UrlDealUtil.getRealUrl(RequestCode.SELECT_MEMBERID);
        HttpRequestBean requestBean = new HttpRequestBean(RequestCode.POSTEQUEST, useUrl, this, FriendsListBean.class, RequestCode.SELECT_MEMBERID);
        HttpHandleUtil.executeCommonPost(this, requestBean);
         Tools.showDialog(this);
    }

    @Override
    public void onItemClick(View view, int position) {
        //如果没有添加朋友先添加朋友
        if (DataBean.get(position).getIsAgreeA()==0){
            addFriends(DataBean.get(position).getMemberRID());
            DataBean.get(position).setIsAgreeA(1);
            friendListAdapter.notifyDataSetChanged();
        }else {
            //跳转到任务界面;
            Intent intent = new Intent(this, FriendshelptaskActivity.class);
            intent.putExtra("_id", "" + DataBean.get(position).getMemberRID());
            startActivity(intent);
        }
    }
    @Subscribe
    public void onEvent(MessageEvent event) {
        event.getFinish();
        finish();
    }

    @Override
    protected void onNewIntent(Intent intent) {

        super.onNewIntent(intent);
        finish();
    }

    //扫描二维码返回的数据;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SCANNIN_GREQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    //显示扫描到的内容
                    String content = bundle.getString("result");
                    Tools.showDialog(this);
                    getZingNetData(content);
                }
                break;
        }
    }

    @Override
    public void click(int where) {
        switch (where){
            case 1:
                Intent intent = new Intent();
                intent.setClass(this, CaptureActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent, SCANNIN_GREQUEST_CODE);
                break;
        }
    }

    /**
     * 添加好友
     * POST Wedding/AddFriends?Token={Token}&i_Id={i_Id}
     同意加为好友
     */
    private void addFriends(int memberId){
        String url = UrlDealUtil.getRealUrl(RequestCode.ADDFRIENDS);
        HashMap<String,String> hashMap = new HashMap<>();
        hashMap.put("MemberRID",""+memberId);
        int i_ID=0;
        User user = DataWareHourse.getInstance().getmUser();
        if(user!=null){
            i_ID=user.getData().get(0).getI_Id();
        }
        hashMap.put("MemberID",""+ i_ID);
        HttpRequestBean requestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url, this,CommonResultBean.class,RequestCode.ADDFRIENDS,hashMap);
        HttpHandleUtil.executeCommonPost(this,requestBean);
        Tools.showDialog(this);
    }

    /**
     * POST Wedding/Return_InfoModel?Token={Token}&i_Id={i_Id}
     会员ID返回我的信息
     */
    private void  getZingNetData(String id){
       String url =  Url.BASE+"Return_InfoModel?Token=00"+"&i_Id="+id;
        RequestParams requestParams = new RequestParams(url);
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Tools.dismissWaitDialog();
                Gson mgson = new Gson();
                PersonBean upLoadImage = mgson.fromJson(StrUtil.jsonStr(result),PersonBean.class);
                Intent intent = new Intent(FindHelp.this,AddFrinds_2_Actvitiy.class);
                intent.putExtra(ADDFRIENDSACTIVITY,(Serializable) upLoadImage.getData());
                startActivity(intent);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
